package com_.dxy_test_.zookeeper_.app_status_;

import com_.dxy_test_.zookeeper_.ZkConfig;
import org.I0Itec.zkclient.ZkClient;

/**
 * @author: dangxianyue
 * @date: 2021/4/30 09:21
 *
 * 需求：
 * 不需要监听，服务器上线时自动连接zk，在指定目录下创建临时节点，保存自己的主机和端口信息
 * 掉线的时候，临时节点会自动删除，同时被客户端监听到，给运维人员发送邮件短信
 */
public class ServerDemo {

    private ZkClient zk = null;

    public static void main(String[] args) throws Exception {
        ServerDemo client = new ServerDemo();
        //1:连接 zk
        client.connect();
        //2:创建servers的临时节点
        //IDEA中往main方法中传参的方法：https://blog.csdn.net/sunyufeng22/article/details/120679216
        client.createNode(args[0]);
        //3:保持程序运行
        client.keepRunning();
    }

    private void connect() throws Exception {
        zk = ZkConfig.zkClient;
        if (!zk.exists(ZkConfig.SERVERS_PATH)) {
            zk.createPersistent(ZkConfig.SERVERS_PATH);
        }
    }

    private void createNode(String hostname) throws Exception {
        zk.createEphemeral(ZkConfig.SERVERS_PATH + "/" + hostname, hostname.getBytes());
    }

    private void keepRunning() {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

